<template>
  <div ref="containerRef" :style="{ width: width, height: height }"></div>
</template>

<script setup lang="ts">
import useEchart from '@/hooks/useEchart'

const props = defineProps({
  width: {
    type: String,
    default: '100%'
  },
  height: {
    type: String,
    default: '100%'
  },
  data: {
    type: Array,
    default: () => []
  }
})
const { width, height, data } = toRefs(props)
const containerRef = ref<null | HTMLElement>(null)
const getOption = (pieData: any[] = []) => {
  let colors = pieData.map((item) => {
    return item.color
  })

  let data = pieData.map((item) => {
    return {
      value: item.value,
      name: item.name
    }
  })

  let total = pieData.reduce((a, b) => {
    return a + b.value * 1
  }, 0)

  return {
    // backgroundColor: 'rbg(40,46,72)',
    color: colors,
    title: {
      text: `{nameSty| 充电桩总数}\n{number|${total}}`,
      top: '50%',
      left: '30%',
      textStyle: {
        rich: {
          nameSty: {
            fontSize: 19,
            color: 'white',
            padding: [10, 0]
          },
          number: {
            fontSize: 24,
            color: 'white',
            padding: [4, 0, 0, 20]
          }
        }
      }
    },
    legend: {
      orient: 'vertical',
      right: '10%',
      top: '18%',
      itemGap: 20,
      itemWidth: 16,
      itemHeight: 16,
      icon: 'rect',
      formatter: function (name: string) {
        const currentItem = pieData.find((item) => item.name === name)
        return (
          '{nameSty|' +
          currentItem.name +
          '}\n' +
          '{numberSty|' +
          currentItem.value +
          '个 }' +
          '{preSty|' +
          currentItem.percentage +
          '}'
        )
      },
      textStyle: {
        rich: {
          nameSty: {
            fontSize: 12,
            color: '#FFFFFF',
            padding: [10, 14]
          },
          numberSty: {
            fontSize: 12,
            color: '#40E6ff',
            padding: [0, 0, 0, 14]
          },
          preSty: {
            fontSize: 12,
            color: '#40E6ff'
          }
        }
      }
    },
    series: [
      {
        type: 'pie',
        center: ['40%', '57%'],
        radius: ['30%', '75%'],
        label: {
          show: false
        },
        data: data,
        roseType: 'area'
      }
    ]
  }
}
let chart: any = null
const setupChart = (data: any[]) => {
  if (!chart) {
    chart = useEchart(containerRef.value as HTMLElement)
  }
  chart.setOption(getOption(data))
}

onMounted(() => {
  setupChart(data.value)
})
watch(
  () => data.value,
  (newData) => {
    containerRef.value && setupChart(newData)
  }
)
</script>

<style lang="scss"></style>
